//
//  CurrentVC.m
//  ChampoinPeso
//
//  Created by mac on 2025/4/2.
//

#import "CurrentVC.h"

@implementation CurrentVC
+ (UIViewController *)cl_findBestViewController:(UIViewController *)vc{
    
    if (vc.presentedViewController) {
        
        // Return presented view controller
        return [self cl_findBestViewController:vc.presentedViewController];
        
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0){
            return [self cl_findBestViewController:svc.viewControllers.lastObject];
        }else{
            return vc;
        }
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0){
            return [self cl_findBestViewController:svc.topViewController];
        }else{
            return vc;
        }
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0){
            return [self cl_findBestViewController:svc.selectedViewController];
        }else{
            return vc;
        }
    } else {
        
        // Unknown view controller type, return last child view controller
        return vc;
        
    }
    
}

+ (UIViewController *)cl_currentViewController{
    
    // Find best view controller
    UIViewController* viewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    return [CurrentVC cl_findBestViewController:viewController];
    
}

@end
